

const fs = require("fs");

// 写入文件
function write (jsonStr) {
    fs.writeFile("./db/db.json", jsonStr,  function(err) {
        if (err) {
            return console.error(err);
        }
    });
}
// 读取文件
function read () {
    var data = fs.readFileSync("./db/db.json");
    let obj = JSON.parse(JSON.stringify(JSON.parse(data)));
    return obj;
}
// 获取列表
function getlist () {
    return read();
}
// 添加
function add (obj) {
    let data = read();
    console.log('读取到的文件', data)
    data.code = 0;
    if (!data.total) {
        data.total = 1;
    } else {
        data.total = data.total + 1;
    }
    if (!data.list) {
        data.list = []
    }
    obj.id = '#' + Math.random().toString(26).substr(8);
    obj.createTime = (new Date()).toLocaleTimeString();

    data.list.push(obj)
    write(JSON.stringify(data));
    return data;
}
// 删除
function del (id) {
    let data = read();
    data.code = 0;
    if (!data.list || !data.list.length) {
        data.total = 0;
        return data;
    }
    data.list.forEach(function (item, i, arr) {
        if (id === item.id) {
            data.total = data.total - 1;
            arr = arr.splice(i, 1);
            return;
        }
    })
    write(JSON.stringify(data));
    return data;
} 
// 修改
function modify (val) {
    let data = read();
    data.code = 0;
    if (!data.list || !data.list.length) {
        data.total = 0;
        return {};
    }
    data.list.find((item, i, arr) => {
        if (item.id === val.id) {
            val.createTime = (new Date()).toLocaleTimeString();
            arr = arr.splice(i, 1, val);
            return ;
        }
    })
    write(JSON.stringify(data));
    return data;
} 

module.exports = {
    getlist,
    add,
    del,
    modify,
}